﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SN.Data;
using System.Data;
using System.Text;
using Agro.Models;
using System.Reflection;
using System.Diagnostics;
using Agro.Services;
using Agro.Library;
using System.Drawing;
using Ninject;
using Newtonsoft.Json;
using SN.Core;
using System.Web.Script.Serialization;
using System.Web.Security;
using System.IO;

namespace Agro.Web.Areas.DataManage.Controllers
{
    public class ReportController : BaseController
    {
        [Inject]
        public IReportService ReportService { get; set; }

        public ActionResult Index(int id, string checkdata)
        {
            ViewBag.SubmitInfoId = id;
            ViewBag.CheckData = checkdata;//用于表示加载页面后是否校验数据
            T_SubmitInfo submitInfo = ReportService.GetEntity<T_SubmitInfo>(T_SubmitInfo._.SubmitInfo_ID == id);
            T_Organization organize = ReportService.GetEntity<T_Organization>(T_Organization._.Organization_ID == submitInfo.SubmitInfo_OrganizationID);

            ViewBag.OrganizeName = organize.Organization_Name;
            ViewBag.auth = Request.Cookies[FormsAuthentication.FormsCookieName] == null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value;
            ViewBag.GUID = Guid.NewGuid().ToString().Replace("-", "");
            ViewBag.H = ReportService.GetReprotFormat(id, CurrUser);
            return View();
        }
        public ActionResult ReportList(string reportid)
        {
            //IDictionary<string, DateTime> GetAllDeadline = ReportService.GetAllDeadline();
            //先默认一下ViewBag的当前年月季。
            ViewBag.CurYear = DateTime.Now.Year;
            ViewBag.CurMonth = (DateTime.Now.Month - 1).ToString("00");
            ViewBag.CurSeason = Math.Ceiling((Convert.ToDecimal(DateTime.Now.Month) / 3)).ToString("00");


            List<KeyValuePair<string, string>> ListMonth = new List<KeyValuePair<string, string>>();
            ListMonth.Add(new KeyValuePair<string, string>("", ""));
            for (int i = 1; i <= 12; i++)
            {
                ListMonth.Add(new KeyValuePair<string, string>(i.ToString("00"), i.ToString("00") + "月"));
            }
            List<KeyValuePair<string, string>> ListYear = new List<KeyValuePair<string, string>>();
            ListYear.Add(new KeyValuePair<string, string>("", ""));
            ListYear.Add(new KeyValuePair<string, string>(DateTime.Now.AddYears(-5).ToString("yyyy"), DateTime.Now.AddYears(-5).ToString("yyyy")));
            ListYear.Add(new KeyValuePair<string, string>(DateTime.Now.AddYears(-4).ToString("yyyy"), DateTime.Now.AddYears(-4).ToString("yyyy")));
            ListYear.Add(new KeyValuePair<string, string>(DateTime.Now.AddYears(-3).ToString("yyyy"), DateTime.Now.AddYears(-3).ToString("yyyy")));
            ListYear.Add(new KeyValuePair<string, string>(DateTime.Now.AddYears(-2).ToString("yyyy"), DateTime.Now.AddYears(-2).ToString("yyyy")));
            ListYear.Add(new KeyValuePair<string, string>(DateTime.Now.AddYears(-1).ToString("yyyy"), DateTime.Now.AddYears(-1).ToString("yyyy")));
            ListYear.Add(new KeyValuePair<string, string>(DateTime.Now.ToString("yyyy"), DateTime.Now.ToString("yyyy")));
            ListYear.Add(new KeyValuePair<string, string>(DateTime.Now.AddYears(1).ToString("yyyy"), DateTime.Now.AddYears(1).ToString("yyyy")));
            ListYear.Add(new KeyValuePair<string, string>(DateTime.Now.AddYears(2).ToString("yyyy"), DateTime.Now.AddYears(2).ToString("yyyy")));
            //季度
            List<KeyValuePair<string, string>> ListSeason = new List<KeyValuePair<string, string>>();
            ListSeason.Add(new KeyValuePair<string, string>("", ""));
            for (int i = 1; i <= 4; i++)
            {
                ListSeason.Add(new KeyValuePair<string, string>(i.ToString("00"), i.ToString("00") + "季度"));
            }
            //上报状态，0:未上报;1:已上报;2:已汇总
            List<KeyValuePair<string, string>> List_State = new List<KeyValuePair<string, string>>();
            List_State.Add(new KeyValuePair<string, string>("", ""));
            List_State.Add(new KeyValuePair<string, string>("0", "未上报"));
            List_State.Add(new KeyValuePair<string, string>("1", "已上报"));
            //List_State.Add(new KeyValuePair<string, string>("2", "已汇总"));

            ViewBag.List_State = List_State;

            ViewBag.REPORTID = reportid; //必须写
            //报表周期 
            string Cycle = ReportService.GetField<T_Report>(T_Report._.Report_Cycle, T_Report._.Report_ID == reportid).ToString();
            ViewBag.Cycle = Cycle;
            ViewBag.ListYear = ListYear;

            if (Cycle == "01") //月报
            {
                ViewBag.ListMonth = ListMonth;

                if (DateTime.Now.Month == 1)//如果是元月，往前推一个月，就要变成去年12月
                {
                    ViewBag.CurMonth = 12.ToString("00");
                    ViewBag.CurYear = DateTime.Now.Year - 1;
                }
                else
                {
                    ViewBag.CurMonth = (DateTime.Now.Month - 1).ToString("00");
                    ViewBag.CurYear = DateTime.Now.Year;
                }
            }



            else if (Cycle == "02")//季报
            {
                ViewBag.ListMonth = ListSeason;

                if ((int)Math.Ceiling((Convert.ToDecimal(DateTime.Now.Month) / 3)) == 1)//如果当前为第一季度，则上季度为去年四季度。
                {
                    ViewBag.CurSeason = "04";
                    ViewBag.CurYear = DateTime.Now.Year - 1;
                }
                else
                {
                    ViewBag.CurSeason = (Math.Ceiling((Convert.ToDecimal(DateTime.Now.Month) / 3)) - 1).ToString("00");
                    ViewBag.CurYear = DateTime.Now.Year;
                }
            }

            else//年报
            {
                ViewBag.CurYear = DateTime.Now.Year - 1;
            }



            ViewBag.NSRWQWReportID = (string)System.Configuration.ConfigurationManager.AppSettings["NSYWQWReportID"];
            ViewBag.XXNYQYJBReportID = (string)System.Configuration.ConfigurationManager.AppSettings["XXNYQYJBReportID"];

            ViewBag.NYCYHLTQYNBReportID = (string)System.Configuration.ConfigurationManager.AppSettings["NYCYHLTQYNBReportID"];

            //龙头企业季报
            ViewBag.NYCYHLTQYJBReportID = (string)System.Configuration.ConfigurationManager.AppSettings["NYCYHLTQYJBReportID"];
            ViewBag.CurrOrganizationID = CurrUser.UserInfo.User_OrganizationID;


            return View();
        }

        public ActionResult ReportGetList(string reportid, QueryBase query)
        {
            WhereClip wclip = WhereClip.All;
            string querydata = Request["queryData"];



            Dictionary<string, string> dic = WebUtility.ConvertQueryToDictionary(querydata);
            foreach (KeyValuePair<string, string> item in dic)
            {
                switch (item.Key)
                {
                    case "ListYear":
                        wclip = wclip && T_SubmitInfo._.SubmitInfo_Year == item.Value;
                        break;
                    case "ListMonth":
                        wclip = wclip && T_SubmitInfo._.SubmitInfo_Month == item.Value;
                        break;
                    case "SubmitInfo_State":
                        wclip = wclip && T_SubmitInfo._.SubmitInfo_State == item.Value;
                        break;
                    case "OrganizationName":
                        wclip = wclip && T_Organization._.Organization_Name.Contains(item.Value.Trim());
                        break;
                    default:
                        break;
                }
            }
            if (reportid != null)
            {
                T_Report report = ReportService.GetEntity<T_Report>(T_Report._.Report_ID == reportid);

                //如果报表的下发类型为2，即只有企业填报，管理部门能看所有下级部门。
                if (report.Report_Xflx == "2")
                {
                    wclip = wclip && T_SubmitInfo._.SubmitInfo_ReportID == reportid && new WhereClip("T_SubmitInfo.SubmitInfo_OrganizationID in ( SELECT  Organization_ID from GetAllChildOrg(" + CurrUser.UserInfo.User_OrganizationID.ToString() + ")) "); 
                }
                else
                {

                    if (CurrUser.UserInfo.IsAdmin())//如果是管理员，则显示所有报表， 不再只显示子级报表。
                    { wclip = wclip && T_SubmitInfo._.SubmitInfo_ReportID == reportid; }
                    else//否则只显示本级与子级
                    {
                        //查询下级单位与本单位
                        IList<T_Organization> ListTemp = ReportService.GetChildOrg(CurrUser.UserInfo.User_OrganizationID.ToString());
                        //childOrgList.Select(m => m.Organization_ID).ToArray()
                        if (ListTemp.Count > 0)
                        {
                            wclip = wclip && WhereClip.Bracket(T_SubmitInfo._.SubmitInfo_OrganizationID == CurrUser.UserInfo.User_OrganizationID || T_SubmitInfo._.SubmitInfo_OrganizationID.In(ListTemp.Select(m => m.Organization_ID).ToArray()))
                                          && T_SubmitInfo._.SubmitInfo_ReportID == reportid;
                        }
                        else
                        {
                            wclip = wclip && T_SubmitInfo._.SubmitInfo_OrganizationID == CurrUser.UserInfo.User_OrganizationID && T_SubmitInfo._.SubmitInfo_ReportID == reportid;
                        }
                    }
                }
            }
            var list = ReportService.ReportGetList(query, wclip);
            return JqGrid(list, query);
        }

        public ActionResult Save(string reportid, string zbbh, string dwid, string year, string month, string day,
            string cycle, string val, string state, string SubmitInfo_ID)
        {
            T_ZBSJ detail = new T_ZBSJ();
            detail.ZBSJ_ReportID = reportid;
            detail.ZBSJ_ZBBH = zbbh.Replace("[Calc]", "");
            detail.ZBSJ_DWID = dwid;
            detail.ZBSJ_YEAR = year;
            detail.ZBSJ_MONTH = month ?? "";
            detail.ZBSJ_DAY = day;
            detail.ZBSJ_Cycle = cycle;
            detail.ZBSJ_Value = val;
            detail.SubmitInfoID = Convert.ToInt32(SubmitInfo_ID);

            int i = 0;
            if (state == "0")//state为0时，即可编辑状态
            {
                i = ReportService.SaveZBSJ(detail, CurrUser);
            }
            return Json(i.ToString());
        }

        [HttpPost]
        public ActionResult ChangeSubmitState(string submitinfoid, string state)
        {
            string msg = string.Empty;
            int i = ReportService.updateState(submitinfoid, state, CurrUser, out msg);
            if (i == 2)
            {
                msg = "数据逻辑校验失败！请打开报表点击【校验】按钮重新校验查看详细错误";
                return Json(msg);
            }
            if (msg.Length > 0)
            {
                return Json(msg);
            }
            return Json("");
        }

        [HttpPost]
        public ActionResult CheckDataLogic(int submitInfoId)
        {
            List<string> msgList = new List<string>();
            T_SubmitInfo submitinfo = ReportService.GetEntity<T_SubmitInfo>(T_SubmitInfo._.SubmitInfo_ID == submitInfoId);
            T_Report report = ReportService.GetEntity<T_Report>(T_Report._.Report_ID == submitinfo.SubmitInfo_ReportID);

            //如果下发类型是2，即只有企业填报，管理部门只能看的报表，可能会有复合校验公式如">=a+b"
            if (report.Report_Xflx == "2")
            {
                var errorZBList1 = ReportService.CheckFhZBValue(submitInfoId.ToString(), out msgList);
                return Json(new { ErrorZBList = errorZBList1, ErrMsgList = msgList });
            }
            else
            {
                var errorZBList2 = ReportService.CheckZBValue(submitInfoId.ToString(), out msgList);
                return Json(new { ErrorZBList = errorZBList2, ErrMsgList = msgList });
            }
            
        }

        [HttpPost]
        public ActionResult CalcFormulaZB(int submitInfoId)
        {
            ReportService.CalcFormulaZBValue(submitInfoId, CurrUser);
            return SNJson(string.Empty);
        }

        public ActionResult SumReportData(string reportid, string year, string month, string jd, string org)
        {
            string Msg = string.Empty;

            T_Report report = ReportService.GetEntity<T_Report>(T_Report._.Report_ID == reportid);
            //如果报表id为000045，或000048 ，则不能汇总，因为这两张表是不可以汇总的。
            if (report.Report_Xflx == "2")
                return Json("该报表管理部门不能汇总！");
            Msg = ReportService.CollectReport(reportid, CurrUser.UserInfo.User_OrganizationID.ToString(), year, month, jd, "", CurrUser, org);
            return Json(Msg);
        }

        public ActionResult NSRWQWQYYL(int id)
        {
            ViewBag.SubmitInfoID = id;
            ViewBag.auth = Request.Cookies[FormsAuthentication.FormsCookieName] == null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value;
            ViewBag.GUID = Guid.NewGuid().ToString().Replace("-", "");
            //该报表的可编辑状态，如果不是录入状态，或非本部门人员打开，不能编辑，值为0，可编辑为1
            T_SubmitInfo SubmitInfo = ReportService.GetEntity<T_SubmitInfo>(T_SubmitInfo._.SubmitInfo_ID == id);
            //T_Organization Organization = ReportService.GetEntity<T_Organization>(T_Organization._.Organization_ID == SubmitInfo.SubmitInfo_OrganizationID);

            //ViewBag.Organization = Organization;

            if (SubmitInfo.SubmitInfo_OrganizationID == CurrUser.UserInfo.User_OrganizationID.ToString() && SubmitInfo.SubmitInfo_State == "0")
                ViewBag.edittype = "1";
            else
                ViewBag.edittype = "0";
            return View();
        }

        [HttpPost]
        public ActionResult NSRWQWQYYL_GetList(int id, QueryBase query)
        {
            WhereClip where = T_5000W._.SubmitInfoID == id;
            if (query == null || query.rows == 0)
            {
                var dt = ReportService.Get5000WReportDT(where, query);
                return JqGrid(dt, query);
            }
            else
            {
                var list = ReportService.GetEntityList<T_5000W>(where, query);
                return JqGrid(list, query);
            }
        }

        //导出报表
        public ActionResult ExportReport(string SubmitInfoId)
        {
            string msg = string.Empty;
            T_SubmitInfo submitinfo = ReportService.GetEntity<T_SubmitInfo>(T_SubmitInfo._.SubmitInfo_ID == SubmitInfoId);
            var stream = ReportService.GetExcelStream(SubmitInfoId, CurrUser, out msg);
            if (msg.Length > 0)
            {
                return Content("<script>alert('" + msg + "');window.history.go(-1);</script>");
            }
            T_Report report = ReportService.GetEntity<T_Report>(T_Report._.Report_ID == submitinfo.SubmitInfo_ReportID);
            return Excel(stream, HttpUtility.UrlEncode(report.Report_Name, System.Text.Encoding.UTF8));
        }

        public ActionResult ExportNSRWQWReport(int id)
        {
            var stream = ReportService.Get5000WReportStream(id);
            T_SubmitInfo submitInfo = ReportService.GetEntity<T_SubmitInfo>(T_SubmitInfo._.SubmitInfo_ID == id);
            T_Report report = ReportService.GetEntity<T_Report>(T_Report._.Report_ID == submitInfo.SubmitInfo_ReportID);
            return Excel(stream, HttpUtility.UrlEncode(report.Report_Name, System.Text.Encoding.UTF8));
        }



        [HttpPost]
        public ActionResult Save5000WReport()
        {
            string msg = string.Empty;
            string strdetail = Request.Form["detail"];
            string strdataList = Request.Form["dataList"];
            FormCollection collection = WebUtility.ConvertToFormCollection(strdetail);
            List<T_5000W> detailList = new List<T_5000W>();
            var jss = new JavaScriptSerializer();
            detailList = (List<T_5000W>)jss.Deserialize(strdataList, typeof(List<T_5000W>));
            foreach (var item in detailList)
            {
                if (!TryValidateModel(item)) { }
            }
            ReportService.Save5000WReport(detailList, out msg);
            return SNJson(msg);
        }

        /// <summary>
        /// 导入模版类报表数据
        /// </summary>
        /// <param name="FileData"></param>
        /// <param name="GUID"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult importReport(HttpPostedFileBase FileData, string GUID, string submitInfoId)
        {
            string fileName = string.Empty;
            string Msg = string.Empty;
            fileName = Path.GetFileName(FileData.FileName);
            try
            {
                using (MemoryStream templeteStream = new MemoryStream())
                {
                    int FileLen;
                    FileLen = FileData.ContentLength;
                    byte[] bytes = new byte[FileLen];
                    FileData.InputStream.Read(bytes, 0, FileLen);
                    templeteStream.Write(bytes, 0, FileLen);
                    Msg = ReportService.importReport(templeteStream, submitInfoId);
                }
            }
            catch (Exception ex)
            {
                Msg = ex.Message;
            }

            return Content(Msg);

        }

        /// <summary>
        /// 非模版类报表通用导入
        /// </summary>
        /// <param name="FileData"></param>
        /// <param name="GUID"></param>
        /// <param name="submitInfoId">上报报表id</param>
        /// <param name="colModels">jqgrid列名集合</param>
        /// <param name="query"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult importReportExA(HttpPostedFileBase FileData, string GUID, string submitInfoId, string colModels, QueryBase query)
        {
            string Msg = string.Empty;
            DataTable table = null;
            try
            {
                using (MemoryStream templeteStream = new MemoryStream())
                {
                    int FileLen;
                    FileLen = FileData.ContentLength;
                    byte[] bytes = new byte[FileLen];
                    FileData.InputStream.Read(bytes, 0, FileLen);
                    templeteStream.Write(bytes, 0, FileLen);
                    table = ReportService.importReportExA(templeteStream, submitInfoId, colModels);

                    //List<dynamic> colModels1 = new List<dynamic>();
                    //foreach (DataColumn col in table.Columns)
                    //{
                    //    colModels1.Add(new
                    //    {
                    //        label = col.Caption,
                    //        name = col.ColumnName,
                    //        width = "100",
                    //        align = col.DataType.IsValueType ? "right" : "left"
                    //    });
                    //}
                    return JqGrid(table, query);
                    //return SNJson(table, Msg);
                }
            }
            catch (Exception ex)
            {
                Msg = ex.Message;
                return SNJson(Msg);
            }


        }


        /// <summary>
        /// 河南农业产业化龙头企业季报表导入，因为表头比较特殊，显示字段名称相同，用通用的方法无法处理,此方法直接按数据在表格中的位置导入，不判断列是否一致
        /// </summary>
        /// <param name="FileData"></param>
        /// <param name="GUID"></param>
        /// <param name="submitInfoId">上报报表id</param>
        /// <param name="colModels">jqgrid列名集合</param>
        /// <param name="query"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult importReportExB(HttpPostedFileBase FileData, string GUID, string submitInfoId, string colModels, QueryBase query)
        {
            string Msg = string.Empty;
            DataTable table = null;
            try
            {
                using (MemoryStream templeteStream = new MemoryStream())
                {
                    int FileLen;
                    FileLen = FileData.ContentLength;
                    byte[] bytes = new byte[FileLen];
                    FileData.InputStream.Read(bytes, 0, FileLen);
                    templeteStream.Write(bytes, 0, FileLen);
                    table = ReportService.importReportExB(templeteStream, submitInfoId, colModels);

                    //List<dynamic> colModels1 = new List<dynamic>();
                    //foreach (DataColumn col in table.Columns)
                    //{
                    //    colModels1.Add(new
                    //    {
                    //        label = col.Caption,
                    //        name = col.ColumnName,
                    //        width = "100",
                    //        align = col.DataType.IsValueType ? "right" : "left"
                    //    });
                    //}
                    return JqGrid(table, query);
                    //return SNJson(table, Msg);
                }
            }
            catch (Exception ex)
            {
                Msg = ex.Message;
                return SNJson(Msg);
            }
        }





        public ActionResult XXNYQYJB(int id)
        {
            ViewBag.SubmitInfoID = id;
            ViewBag.auth = Request.Cookies[FormsAuthentication.FormsCookieName] == null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value;
            ViewBag.GUID = Guid.NewGuid().ToString().Replace("-", "");

            //该报表的可编辑状态，如果不是录入状态，或非本部门人员打开，不能编辑，值为0，可编辑为1
            T_SubmitInfo SubmitInfo = ReportService.GetEntity<T_SubmitInfo>(T_SubmitInfo._.SubmitInfo_ID == id);
            T_Organization Organization = ReportService.GetEntity<T_Organization>(T_Organization._.Organization_ID == SubmitInfo.SubmitInfo_OrganizationID);

            ViewBag.Organization = Organization;

            if (SubmitInfo.SubmitInfo_OrganizationID == CurrUser.UserInfo.User_OrganizationID.ToString() && SubmitInfo.SubmitInfo_State == "0")
                ViewBag.edittype = "1";
            else
                ViewBag.edittype = "0";
            return View();
        }


        [HttpPost]
        public ActionResult XXNYQYJB_GetList(int id, QueryBase query)
        {
            WhereClip where = T_XXNYQYJB._.SubmitInfoID == id;
            if (query == null || query.rows == 0)
            {
                var dt = ReportService.GetXXNYQYJBDT(where, query);
                return JqGrid(dt, query);
            }
            else
            {
                var list = ReportService.GetEntityList<T_XXNYQYJB>(where, query);
                return JqGrid(list, query);
            }
        }


        [HttpPost]
        public ActionResult SaveXXNYQYJB()
        {
            string msg = string.Empty;
            string strdetail = Request.Form["detail"];
            string strdataList = Request.Form["dataList"];
            FormCollection collection = WebUtility.ConvertToFormCollection(strdetail);
            List<T_XXNYQYJB> detailList = new List<T_XXNYQYJB>();
            var jss = new JavaScriptSerializer();
            detailList = (List<T_XXNYQYJB>)jss.Deserialize(strdataList, typeof(List<T_XXNYQYJB>));
            foreach (var item in detailList)
            {
                item.OrganizeID = CurrUser.UserInfo.User_OrganizationID;
                if (!TryValidateModel(item)) { }
            }
            ReportService.SaveXXNYQYJB(detailList, out msg);
            return SNJson(msg);
        }

        public ActionResult ExportXXNYQYJB(int id)
        {
            var stream = ReportService.GetXXNYQYJBStream(id);
            T_SubmitInfo submitInfo = ReportService.GetEntity<T_SubmitInfo>(T_SubmitInfo._.SubmitInfo_ID == id);
            T_Report report = ReportService.GetEntity<T_Report>(T_Report._.Report_ID == submitInfo.SubmitInfo_ReportID);
            return Excel(stream, HttpUtility.UrlEncode(report.Report_Name, System.Text.Encoding.UTF8));
        }





        //农业产业化龙头企业季报(ADD 2013-07-23 xiaoping)
        public ActionResult NYCYHLTQYJB(int id)
        {
            ViewBag.SubmitInfoID = id;
            ViewBag.auth = Request.Cookies[FormsAuthentication.FormsCookieName] == null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value;
            ViewBag.GUID = Guid.NewGuid().ToString().Replace("-", "");
            //该报表的可编辑状态，如果不是录入状态，或非本部门人员打开，不能编辑，值为0，可编辑为1
            T_SubmitInfo SubmitInfo = ReportService.GetEntity<T_SubmitInfo>(T_SubmitInfo._.SubmitInfo_ID == id);
            T_Organization Organization = ReportService.GetEntity<T_Organization>(T_Organization._.Organization_ID == SubmitInfo.SubmitInfo_OrganizationID);

            ViewBag.Organization = Organization;
            if (SubmitInfo.SubmitInfo_OrganizationID == CurrUser.UserInfo.User_OrganizationID.ToString() && SubmitInfo.SubmitInfo_State == "0")
                ViewBag.edittype = "1";
            else
                ViewBag.edittype = "0";
            return View();

        }
        public ActionResult NYCYHLTQYJB_GetList(int id, QueryBase query)
        {
            WhereClip where = T_NYCYHLTQYJB._.SubmitInfoID == id;
            if (query == null || query.rows == 0)
            {
                var dt = ReportService.GetNYCYHLTQYJBDT(where, query);
                return JqGrid(dt, query);
            }
            else
            {
                var list = ReportService.GetEntityList<T_NYCYHLTQYJB>(where, query);
                return JqGrid(list, query);
            }
        }
        [HttpPost]
        public ActionResult SaveNYCYHLTQYJB()
        {
            string msg = string.Empty;
            string strdetail = Request.Form["detail"];
            string strdataList = Request.Form["dataList"];
            FormCollection collection = WebUtility.ConvertToFormCollection(strdetail);
            List<T_NYCYHLTQYJB> detailList = new List<T_NYCYHLTQYJB>();
            var jss = new JavaScriptSerializer();
            detailList = (List<T_NYCYHLTQYJB>)jss.Deserialize(strdataList, typeof(List<T_NYCYHLTQYJB>));
            foreach (var item in detailList)
            {
                if (!TryValidateModel(item)) { }
            }
            ReportService.SaveNYCYHLTQYJB(detailList, out msg);
            return SNJson(msg);
        }

        #region 农业化龙头企业季报
        /// <summary>
        /// 农业化龙头企业季报
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ExportNYCYHLTQYJBReport(int id, string Organization_Level)
        {
            string Organization_Levelname;

            switch (Organization_Level)
            {
                case "1":
                    Organization_Levelname = "国家级龙头企业";
                    break;
                case "2":
                    Organization_Levelname = "省级龙头企业";
                    break;
                case "3":
                    Organization_Levelname = "市级龙头企业";
                    break;
                default:
                    Organization_Levelname = "";
                    break;
            }
            var stream = ReportService.GetNYCYHLTQYJBStream(id, Organization_Level);
            T_SubmitInfo submitInfo = ReportService.GetEntity<T_SubmitInfo>(T_SubmitInfo._.SubmitInfo_ID == id);
            T_Report report = ReportService.GetEntity<T_Report>(T_Report._.Report_ID == submitInfo.SubmitInfo_ReportID);

            return Excel(stream, HttpUtility.UrlEncode(report.Report_Name + Organization_Levelname, System.Text.Encoding.UTF8));
        }
        #endregion

        #region 农业化龙头企业年报...

        public ActionResult NYCYHLTQYNB(int id)
        {
            ViewBag.SubmitInfoID = id;
            ViewBag.auth = Request.Cookies[FormsAuthentication.FormsCookieName] == null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value;
            ViewBag.GUID = Guid.NewGuid().ToString().Replace("-", "");
            //该报表的可编辑状态，如果不是录入状态，或非本部门人员打开，不能编辑，值为0，可编辑为1
            T_SubmitInfo SubmitInfo = ReportService.GetEntity<T_SubmitInfo>(T_SubmitInfo._.SubmitInfo_ID == id);
            T_Organization Organization = ReportService.GetEntity<T_Organization>(T_Organization._.Organization_ID == SubmitInfo.SubmitInfo_OrganizationID);
            ViewBag.Organization = Organization;
            if (SubmitInfo.SubmitInfo_OrganizationID == CurrUser.UserInfo.User_OrganizationID.ToString() && SubmitInfo.SubmitInfo_State == "0")
                ViewBag.edittype = "1";
            else
                ViewBag.edittype = "0";

            return View();
        }


        [HttpPost]
        public ActionResult LTQYNB1_GetList(int submitInfoId, QueryBase query)
        {
            WhereClip where = T_NYCYHLTQYNB1._.SubmitInfoID == submitInfoId;
            var dataList = ReportService.GetPageList<T_NYCYHLTQYNB1>(where, query);
            return JqGrid(dataList, query);
        }

        [HttpPost]
        public ActionResult LTQYNB2_GetList(int submitInfoId, QueryBase query)
        {
            WhereClip where = T_NYCYHLTQYNB2._.SubmitInfoID == submitInfoId;
            var dataList = ReportService.GetPageList<T_NYCYHLTQYNB2>(where, query);
            return JqGrid(dataList, query);
        }

        [HttpPost]
        public ActionResult LTQYNB3_GetList(int submitInfoId, QueryBase query)
        {
            WhereClip where = T_NYCYHLTQYNB3._.SubmitInfoID == submitInfoId;
            var dataList = ReportService.GetPageList<T_NYCYHLTQYNB3>(where, query);
            return JqGrid(dataList, query);
        }

        [HttpPost]
        public ActionResult LTQYNB4_GetList(int submitInfoId, QueryBase query)
        {
            WhereClip where = T_NYCYHLTQYNB4._.SubmitInfoID == submitInfoId;
            var dataList = ReportService.GetPageList<T_NYCYHLTQYNB4>(where, query);
            return JqGrid(dataList, query);
        }

        [HttpPost]
        public ActionResult LTQYNB5_GetList(int submitInfoId, QueryBase query)
        {
            WhereClip where = T_NYCYHLTQYNB5._.SubmitInfoID == submitInfoId;
            var dataList = ReportService.GetPageList<T_NYCYHLTQYNB5>(where, query);
            return JqGrid(dataList, query);
        }

        [HttpPost]
        public ActionResult LTQYNB6_GetList(int submitInfoId, QueryBase query)
        {
            WhereClip where = T_NYCYHLTQYNB6._.SubmitInfoID == submitInfoId;
            var dataList = ReportService.GetPageList<T_NYCYHLTQYNB6>(where, query);
            return JqGrid(dataList, query);
        }

        [HttpPost]
        public ActionResult LTQYNB7_GetList(int submitInfoId, QueryBase query)
        {
            WhereClip where = T_NYCYHLTQYNB7._.SubmitInfoID == submitInfoId;
            var dataList = ReportService.GetPageList<T_NYCYHLTQYNB7>(where, query);
            return JqGrid(dataList, query);
        }

        [HttpPost]
        public ActionResult Save_LTQYNB(int submitInfoID)
        {
            string strdataList1 = Request.Form["dataList1"];
            string strdataList2 = Request.Form["dataList2"];
            string strdataList3 = Request.Form["dataList3"];
            string strdataList4 = Request.Form["dataList4"];
            string strdataList5 = Request.Form["dataList5"];
            string strdataList6 = Request.Form["dataList6"];
            string strdataList7 = Request.Form["dataList7"];
            JavaScriptSerializer jss = new JavaScriptSerializer();
            string msg = string.Empty;
            ReportService.SaveNYCYHLTQYNB(new T_NYCYHLTQYNB
            {
                SubmitInfoID = submitInfoID,
                T_NYCYHLTQYNB1_List = jss.Deserialize<List<T_NYCYHLTQYNB1>>(strdataList1),
                T_NYCYHLTQYNB2_List = jss.Deserialize<List<T_NYCYHLTQYNB2>>(strdataList2),
                T_NYCYHLTQYNB3_List = jss.Deserialize<List<T_NYCYHLTQYNB3>>(strdataList3),
                T_NYCYHLTQYNB4_List = jss.Deserialize<List<T_NYCYHLTQYNB4>>(strdataList4),
                T_NYCYHLTQYNB5_List = jss.Deserialize<List<T_NYCYHLTQYNB5>>(strdataList5),
                T_NYCYHLTQYNB6_List = jss.Deserialize<List<T_NYCYHLTQYNB6>>(strdataList6),
                T_NYCYHLTQYNB7_List = jss.Deserialize<List<T_NYCYHLTQYNB7>>(strdataList7)
            }, out msg);
            return SNJson(msg);
        }

        //导出
        public ActionResult ExportLTQYNB(int id, string Organization_Level)
        {
            string Organization_Levelname;

            switch (Organization_Level)
            {
                case "1":
                    Organization_Levelname = "国家级龙头企业";
                    break;
                case "2":
                    Organization_Levelname = "省级龙头企业";
                    break;
                case "3":
                    Organization_Levelname = "市级龙头企业";
                    break;
                default:
                    Organization_Levelname = "";
                    break;
            }
            var stream = ReportService.GetNYCYHLTQYNBStream(id, Organization_Level);
            T_SubmitInfo submitInfo = ReportService.GetEntity<T_SubmitInfo>(T_SubmitInfo._.SubmitInfo_ID == id);
            T_Report report = ReportService.GetEntity<T_Report>(T_Report._.Report_ID == submitInfo.SubmitInfo_ReportID);
            return Excel(stream, HttpUtility.UrlEncode(report.Report_Name + Organization_Levelname, System.Text.Encoding.UTF8));
        }


        public ActionResult importLTQYNB(HttpPostedFileBase FileData, string GUID,
           string submitInfoId,
            string colModel1,
            string colModel2,
            string colModel3,
            string colModel4,
            string colModel5,
            string colModel6,
            string colModel7,
            QueryBase query)
        {
            DataSet ds = null;
            string msg = string.Empty;
            try
            {
                using (MemoryStream templeteStream = new MemoryStream())
                {
                    int FileLen;
                    FileLen = FileData.ContentLength;
                    byte[] bytes = new byte[FileLen];
                    FileData.InputStream.Read(bytes, 0, FileLen);
                    templeteStream.Write(bytes, 0, FileLen);
                    ds = ReportService.ImportLTQYNB(templeteStream, submitInfoId,
                        colModel1,
                        colModel2,
                        colModel3,
                        colModel4,
                        colModel5,
                        colModel6,
                        colModel7, out msg);
                    var gridData1 = new
                    {
                        page = 1,
                        total = 1,
                        records = ds.Tables[0].Rows.Count,
                        rows = DataTableToDictionaryList(ds.Tables[0])
                    };
                    var gridData2 = new
                    {
                        page = 1,
                        total = 1,
                        records = ds.Tables[1].Rows.Count,
                        rows = DataTableToDictionaryList(ds.Tables[1])
                    };
                    var gridData3 = new
                    {
                        page = 1,
                        total = 1,
                        records = ds.Tables[2].Rows.Count,
                        rows = DataTableToDictionaryList(ds.Tables[2])
                    };
                    var gridData4 = new
                    {
                        page = 1,
                        total = 1,
                        records = ds.Tables[3].Rows.Count,
                        rows = DataTableToDictionaryList(ds.Tables[3])
                    };
                    var gridData5 = new
                    {
                        page = 1,
                        total = 1,
                        records = ds.Tables[4].Rows.Count,
                        rows = DataTableToDictionaryList(ds.Tables[4])
                    };
                    var gridData6 = new
                    {
                        page = 1,
                        total = 1,
                        records = ds.Tables[5].Rows.Count,
                        rows = DataTableToDictionaryList(ds.Tables[5])
                    };
                    var gridData7 = new
                    {
                        page = 1,
                        total = 1,
                        records = ds.Tables[6].Rows.Count,
                        rows = DataTableToDictionaryList(ds.Tables[6])
                    };
                    var data = new
                    {
                        GridData1 = gridData1,
                        GridData2 = gridData2,
                        GridData3 = gridData3,
                        GridData4 = gridData4,
                        GridData5 = gridData5,
                        GridData6 = gridData6,
                        GridData7 = gridData7
                    };
                    return SNJson(data, msg);
                }
            }
            catch (Exception ex)
            {
                return SNJson(ex.Message);
            }
        }

        private static List<Dictionary<string, object>> DataTableToDictionaryList(DataTable dataTable)
        {
            if (dataTable == null)
                throw new ArgumentNullException("dataTable");
            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
            Dictionary<string, object> row = null;
            foreach (DataRow dr in dataTable.Rows)
            {
                row = new Dictionary<string, object>();
                foreach (DataColumn dc in dataTable.Columns)
                    row.Add(dc.ColumnName, dr[dc.ColumnName]);
                rows.Add(row);
            }
            return rows;
        }
        #endregion

    }
}
